package com.bwt.huffmantree;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HuffmanTree {
    public static void main(String[] args) {
        int[] arr = {13, 7, 8, 3,29, 6, 1};
        Node huffmanTree = createHuffmanTree(arr);
        huffmanTree.prefixOrder();
    }

    /**
     * 创建赫夫曼树的方法
     * @param arr
     * @return 返回创建好的root节点
     * */
    public static Node createHuffmanTree(int[] arr) {
        //遍历arr数组, 创建集合 便于管理
        List<Node> nodes = new ArrayList<>();
        for (int i = 0; i < arr.length; i++) {
            nodes.add(new Node(arr[i]));
        }

        //处理的过程是个循环的过程
        while (nodes.size() > 1) {
            Collections.sort(nodes);

            //取出根节点权值最小的两颗二叉树
            //1. 取出权值最小的节点(二叉树)
            Node left = nodes.get(0);
            //2. 取出权值第二小的节点(二叉树)
            Node right = nodes.get(1);

            //3. 构建一颗新的二叉树
            Node parent = new Node(left.value + right.value);
            parent.left = left;
            parent.right = right;

            //4. 从list中删除 处理过的二叉树
            nodes.remove(left);
            nodes.remove(right);

            //5. 将parent加入list
            nodes.add(parent);
        }
        //返回赫夫曼数的root节点
        return nodes.get(0);
    }
}

//创建节点类
//实现Comparable 接口
class Node implements Comparable<Node> {
    int value; //节点权值
    Node left; //左子节点
    Node right;//右子节点


    //前序遍历
    public void prefixOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.prefixOrder();
        }
        if (this.right != null) {
            this.right.prefixOrder();
        }
    }
    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }


    @Override
    public int compareTo(Node o) {
        //从小到大排序
        return this.value - o.value;
    }
}
